package com.dq.service.messsge.impl;

import com.dq.context.Constant;
import com.dq.exception.customException.AdminException;
import com.dq.domain.message.custome.ServiceMessage;
import com.dq.domain.message.oneself.NoticeMessage;
import com.dq.domain.sys.user.user.base.SysUser;
import com.dq.repository.BaseRepositories;
import com.dq.service.messsge.ServiceMessageService;
import com.dq.service.sys.user.SysUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author cf
 *
 */
@Service
public class ServiceMessageServiceImpl extends BaseRepositories implements ServiceMessageService {
    @Autowired
    private SysUserService sysUserService;

    /**
     * 添加
     * @param serviceMessage
     * @return
     * @throws AdminException
     */
    @Override
    public ServiceMessage save(ServiceMessage serviceMessage)  throws AdminException {
        if(serviceMessage.getWxuser() == null) {
            throw new AdminException("请选择消息接收者");
        }

        serviceMessage.setMessageStatus(NoticeMessage.MessageStatus.noSee);
        serviceMessage.setMessageType(NoticeMessage.MessageType.wxService);

        serviceMessage.setVersion(Constant.VERSION_VALUE);
        serviceMessage.setDeleted(false);
        serviceMessage.setCreateTime(System.currentTimeMillis());
        serviceMessage.setLastModifyTime(System.currentTimeMillis());

        SysUser user = sysUserService.getUser();
        serviceMessage.setCreateUser(user);
        serviceMessage.setUpdateUser(user);

        serviceMessage.setOrg(serviceMessage.getWxuser().getSection());
        if(StringUtils.isBlank(serviceMessage.getTheme())) {
            serviceMessage.setTheme(NoticeMessage.MessageType.wxService.name);
        }

        dao.saveOrModify(serviceMessage);

        return serviceMessage;
    }

    /**
     *修改
     * @param noticeMessage
     * @return
     * @throws AdminException
     */
    @Override
    public ServiceMessage update(ServiceMessage noticeMessage) throws AdminException {
        noticeMessage.setLastModifyTime(System.currentTimeMillis());

        SysUser user = sysUserService.getUser();
        if(user != null) {
            noticeMessage.setUpdateUser(user);
        }

        dao.saveOrModify(noticeMessage);

        return noticeMessage;
    }

}

